<template>

  <el-form-item v-if="type==undefined" :label="label" :prop="prop">
    <el-input v-model="bindValue"
              :placeholder="placeholder" :suffix-icon="suffixIconValue"></el-input>
  </el-form-item>

  <el-form-item v-else-if="type=='number'" :label="label" :prop="prop">
    <el-input v-model="bindValue"
              :placeholder="placeholder" suffix-icon="el-icon-edit el-input__icon"></el-input>
  </el-form-item>

  <el-form-item v-else-if="type=='img'" :label="label" :prop="prop">
    <el-upload
      :headers="getHeaders()"
      :action="getBaseUrl()"
      :show-file-list="false"
      :on-success="uploadPicUrl"
      class="avatar-uploader"
      accept=".jpg,.jpeg,.png,.gif">
      <img v-if="bindValue" :src="bindValue"
           class="picUrl" :style="'width: '+widthValue+';'">
      <i v-else class="el-icon-plus picUrl-uploader-icon"/>
    </el-upload>
  </el-form-item>

  <el-form-item v-else-if="type=='select'&&load==undefined" :label="label" :prop="prop">
    <el-select v-if="type=='select'&&dataLoaded&&load==undefined" v-model="bindValue" clearable
               :placeholder="placeholder">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>
    <el-select v-else-if="type=='select'&&load==undefined&&!dataLoaded" v-model="bindValue" clearable
               :placeholder="placeholder">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>
  </el-form-item>

  <el-form-item v-else-if="type=='select'&&load!=undefined" :label="label"
                :prop="prop">
    <el-select v-if="type=='select'&&dataLoaded&&load!=undefined" v-model="bindValue"
               filterable
               remote
               reserve-keyword
               @clear="getSelectRemoteData"
               :remote-method="getSelectRemoteData"
               clearable :placeholder="placeholder">
      <el-option
        v-for="item in remoteOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>
    <el-select v-else-if="type=='select'&&load!=undefined&&!dataLoaded" v-model="bindValue"
               filterable
               remote
               reserve-keyword
               @clear="getSelectRemoteData"
               :remote-method="getSelectRemoteData"
               clearable :placeholder="placeholder">
      <el-option
        v-for="item in remoteOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>
  </el-form-item>

  <el-form-item v-else-if="type=='cas'" :label="label" :prop="prop">
    <el-cascader v-if="type=='cas'&&dataLoaded" :options="options" v-model="casPath" :props="props" clearable
                 :placeholder="placeholder" @change="handleChange"></el-cascader>
    <el-cascader v-else-if="type=='cas'&&!dataLoaded" :options="options" v-model="casPath" :props="props" clearable
                 :placeholder="placeholder" @change="handleChange"></el-cascader>
  </el-form-item>

  <el-form-item v-else-if="type=='date'" :label="label" :prop="prop">
    <el-date-picker  v-model="bindValue" class="filter-item" style="width: 220px;"
                    type="datetime"
                    :placeholder="placeholder" value-format="yyyy-MM-dd HH:mm:ss"
                    format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
  </el-form-item>
</template>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .picUrl-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .picUrl {
    width: 145px;
    height: 145px;
    display: block;
  }

  .el-form-item .el-input {
    width: 320px;
  }

  .el-form-item .el-select {
    width: 320px;
  }

  .el-form-item .el-cascader {
    width: 320px;
  }
</style>
<script>
  import { uploadPath } from '@/api/storage'  //上传图片
  import { getToken } from '@/util/auth'
  import { setMapStorage, getMapStore } from '@/util/store'
  import { validatenull } from '@/util/validate'
  import { mapGetters } from 'vuex'
  import { recursiveData, multipleChoice } from '@/util/casUtils'
  import { fetchList } from '@/api/dict'

  export default {
    name: 'globalFormItem',
    model: {
      prop: 'modelVal',//指向props的参数名
      event: 'bindModelEvent'//事件名称
    },
    props: {
      'modelVal': '',
      'prop': undefined,
      'label': '',
      'align': undefined,
      'width': undefined,
      'type': undefined,
      'config': undefined,
      'placeholder': '',
      'load': undefined,
      'props': undefined,
      'suffixIcon':undefined
    },
    watch: {
      //监听值变化，再赋值给modelVal
      bindValue: {
        handler(n, o) {
          this.$emit('bindModelEvent', n)
        },
        deep: true //对象内部属性的监听，关键。
      }
    },
    data() {
      return {
        listQuery: {
          page: 1,
          limit: 50,
          module: this.config.module,
          componentName: this.config.componentName,
          fieldName: this.prop
        },
        listRemoteQuery: {
          page: 1,
          limit: 50
        },
        storageKey: this.config.module + this.config.componentName + this.prop,
        casStorageKey: 'cas:' + this.config.module + this.config.componentName + this.prop,
        bindValue: this.modelVal,
        widthValue: this.width,
        isLoad: false,
        casPath: [],
        dataLoaded: false,
        options: [],
        remoteOptions: [],
        suffixIconValue: this.suffixIcon
      }
    },
    created() {

      if (this.widthValue == undefined) {
        this.widthValue = '250px'
      } else {
        if (this.widthValue.indexOf('%') >= 0) {
          console.log('widthValue', this.widthValue)
        } else if (this.widthValue.indexOf('px') >= 0) {

        } else {
          this.widthValue = this.widthValue + 'px'
        }
      }

      if (this.type == 'select' && this.load == undefined) {
        if (this.bindValue != undefined) {
          this.bindValue = this.bindValue.toString()
        }

        var obj = getMapStore(this.storageKey)
        let newObj = JSON.parse(obj)//深度复制对象
        if (validatenull(newObj) || null == newObj) {
          this.getList()
        } else {
          this.options = newObj
          this.dataLoaded = true
        }
      }

      if (this.type == 'select' && this.load != undefined) {

        if (this.bindValue == undefined || this.bindValue == null) {
          this.bindValue = ''
        }

        if (this.bindValue != undefined) {
          this.bindValue = this.bindValue.toString()
        }

        this.getSelectRemoteData(this.bindValue, false)
      }

      if (this.type == 'cas') {
        this.options.push({ 'label': '父级栏目', 'value': '0', 'children': undefined })
        var obj = getMapStore(this.casStorageKey)
        let newObj = JSON.parse(obj)//深度复制对象
        if (validatenull(newObj) || null == newObj) {
          this.getCasData()
        } else {

          this.dataLoaded = true
          this.options = newObj
          if (this.bindValue != undefined) {
            recursiveData(this.options, this.casPath, [], this.bindValue.toString())

            if (this.casPath == [] || this.casPath == null || this.casPath == '') {
              this.casPath = ['0']
              this.bindValue = this.bindValue.toString()
            }
          } else {
            this.casPath = ['0']
            this.bindValue = 0
          }
          //进行延时数据更新缓存
          this.getCasData()
        }
      }
    },
    computed: {
      ...mapGetters([
        'permissions'
      ])
    },
    filters: {},
    methods: {
      getSelectRemoteData(query, isSearch) {
        if (this.bindValue != undefined && this.bindValue != null && isSearch != undefined) {
          this.listRemoteQuery.value = query
        } else {
          this.listRemoteQuery.label = query
          this.listRemoteQuery.value = undefined
        }

        this.load(this.listRemoteQuery).then((response) => {
          var data = response.data.data
          if (null != data && data.length > 0) {
            this.remoteOptions = data
          } else {
            this.remoteOptions = []
          }
          this.dataLoaded = true
        })
      },
      getCasData() {
        this.load().then((response) => {
            var data = response.data.data
            if (null != data && data.length > 0) {
              this.options[0].children = data
              setMapStorage(this.casStorageKey, this.options)
              if (this.bindValue != undefined) {
                this.casPath = []
                recursiveData(this.options, this.casPath, [], this.bindValue.toString())
                if (this.casPath == [] || this.casPath == null || this.casPath == '') {
                  this.casPath = ['0']
                  this.bindValue = 0
                }
              }
            } else {
              if (this.bindValue == undefined) {
                this.casPath = ['0']
                this.bindValue = 0
              }
            }
            this.dataLoaded = true
          }
        )
      },
      handleChange(value) {
        if(value==null)
        {
          this.casPath = []
          this.bindValue = undefined
          return false
        }

        if (value.length > 0) {
          this.casPath = value
          this.bindValue = value[value.length - 1]
        } else {
          this.casPath = []
          this.bindValue = undefined
        }

      },
      getHeaders() {
        var headers = {
          Authorization: 'Bearer ' + getToken()
        }
        return headers
      },
      getBaseUrl() {
        return uploadPath
      },
      uploadPicUrl(response) {
        this.bindValue = response.data.url
      },
      getList() {
        this.listLoading = false
        this.listQuery.orderByField = 'create_time'
        this.listQuery.isAsc = false
        this.listQuery.fieldName = this.prop
        this.listQuery.module = JSON.stringify(this.config.module)
        this.listQuery.componentName = JSON.stringify(this.config.componentName)
        fetchList(this.listQuery).then(response => {

          var data = response.data.data.records
          if (data.length > 0) {
            this.options = []
            data.forEach(d => {
              this.options.push({
                value: d.value,
                label: d.name
              })
            })
            setMapStorage(this.storageKey, this.options)
          }
          this.dataLoaded = true
        })
      }
    }
  }
</script>
<style>

</style>
